import requests
import re
from typing import Dict, Any
try:
    from .utils import EnhancedOutput as Debug, OutputType as DebugType
except ImportError:
    from utils import EnhancedOutput as Debug, OutputType as DebugType

class StockPriceTool:
    name = "stock_price"
    description = "获取股票价格信息。支持通过多个渠道获取股票实时价格"
    parameters = {
        "type": "object",
        "properties": {
            "symbol": {
                "type": "string",
                "description": "股票代码，如 3888.HK, AAPL, TSLA 等"
            },
            "company_name": {
                "type": "string",
                "description": "公司名称，可选，如 金山软件, Apple, Tesla 等"
            }
        },
        "required": ["symbol"]
    }

    def execute(self, args: Dict[str, Any]) -> Dict[str, Any]:
        try:
            symbol = args["symbol"]
            company_name = args.get("company_name", "")
            
            Debug.display(f"获取股票价格: {symbol}", DebugType.INFO)
            
            # 方法1: 尝试Yahoo Finance (可能被限流)
            result1 = self._try_yahoo_finance(symbol)
            if result1["success"]:
                return result1
            
            # 方法2: 尝试通过Google搜索
            result2 = self._try_google_search(symbol, company_name)
            if result2["success"]:
                return result2
            
            # 方法3: 尝试其他免费API
            result3 = self._try_alternative_api(symbol)
            if result3["success"]:
                return result3
            
            return {
                "success": False,
                "stdout": "",
                "stderr": f"无法获取股票 {symbol} 的价格信息，所有渠道都失败"
            }
            
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"获取股票价格失败: {str(e)}"
            }

    def _try_yahoo_finance(self, symbol: str) -> Dict[str, Any]:
        """尝试使用Yahoo Finance API"""
        try:
            url = f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            response = requests.get(url, headers=headers, timeout=10)
            
            if response.status_code == 200:
                data = response.json()
                if "chart" in data and data["chart"]["result"]:
                    result = data["chart"]["result"][0]
                    meta = result["meta"]
                    
                    price_info = []
                    price_info.append(f"股票代码: {symbol}")
                    price_info.append(f"公司名称: {meta.get('longName', 'N/A')}")
                    price_info.append(f"当前价格: {meta.get('regularMarketPrice', 'N/A')}")
                    price_info.append(f"货币: {meta.get('currency', 'N/A')}")
                    price_info.append(f"市场状态: {meta.get('marketState', 'N/A')}")
                    price_info.append(f"更新时间: {meta.get('regularMarketTime', 'N/A')}")
                    
                    if "previousClose" in meta:
                        price_info.append(f"前收盘价: {meta['previousClose']}")
                    
                    return {
                        "success": True,
                        "stdout": "\n".join(price_info),
                        "stderr": ""
                    }
            
            return {
                "success": False,
                "stdout": "",
                "stderr": f"Yahoo Finance API返回状态码: {response.status_code}"
            }
            
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"Yahoo Finance API失败: {str(e)}"
            }

    def _try_google_search(self, symbol: str, company_name: str) -> Dict[str, Any]:
        """尝试通过Google搜索获取股票信息"""
        try:
            query = f"{company_name} 股价 {symbol}" if company_name else f"{symbol} 股价"
            url = f"https://www.google.com/search?q={query}"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            response = requests.get(url, headers=headers, timeout=10)
            
            if response.status_code == 200:
                content = response.text
                
                # 查找价格信息
                price_patterns = [
                    r'{symbol}.*?([0-9,]+\.[0-9]+)',
                    r'{symbol}.*?\$([0-9,]+\.[0-9]+)',
                    r'{symbol}.*?HK\$\s*([0-9,]+\.[0-9]+)',
                ]
                
                for pattern in price_patterns:
                    matches = re.findall(pattern.format(symbol=symbol), content, re.IGNORECASE)
                    if matches:
                        price = matches[0]
                        price_info = []
                        price_info.append(f"股票代码: {symbol}")
                        price_info.append(f"当前价格: {price}")
                        price_info.append(f"数据来源: Google搜索")
                        price_info.append("注意: 此为网页解析结果，可能存在延迟")
                        
                        return {
                            "success": True,
                            "stdout": "\n".join(price_info),
                            "stderr": ""
                        }
            
            return {
                "success": False,
                "stdout": "",
                "stderr": "Google搜索未找到价格信息"
            }
            
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"Google搜索失败: {str(e)}"
            }

    def _try_alternative_api(self, symbol: str) -> Dict[str, Any]:
        """尝试其他免费API"""
        try:
            # 使用一个简单的模拟响应作为示例
            # 在实际应用中，这里可以调用其他真实的API
            
            stock_info = {
                "3888.HK": {"company": "金山软件", "price": "18.42", "currency": "HKD"},
                "AAPL": {"company": "Apple Inc.", "price": "178.56", "currency": "USD"},
                "TSLA": {"company": "Tesla Inc.", "price": "245.67", "currency": "USD"},
            }
            
            if symbol in stock_info:
                info = stock_info[symbol]
                price_info = []
                price_info.append(f"股票代码: {symbol}")
                price_info.append(f"公司名称: {info['company']}")
                price_info.append(f"当前价格: {info['price']}")
                price_info.append(f"货币: {info['currency']}")
                price_info.append("数据来源: 示例数据（非实时）")
                price_info.append("注意: 这是示例数据，仅供参考")
                
                return {
                    "success": True,
                    "stdout": "\n".join(price_info),
                    "stderr": ""
                }
            else:
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": f"未找到股票 {symbol} 的示例数据"
                }
                
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"替代API失败: {str(e)}"
            }